package com.example.apiproject.intercepter;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.apiproject.annotation.login;
import com.example.apiproject.exception.apiException;
import com.example.apiproject.jwt.jwtutil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private jwtutil jwtUtils;

    public static final String USER_KEY = "id";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        login annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(login.class);
        }else{
            return true;
        }

        if(annotation == null){
            return true;
        }

        //获取用户凭证
        String token = request.getHeader("token");
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }

        //凭证为空
        if(StringUtils.isBlank(token)){
            throw new apiException( "token不能为空", HttpStatus.UNAUTHORIZED.value());
        }
        jwtUtils.verfierToken(token);

//        if(claims == null || jwtUtils.isTokenExpired(claims.getExpiration())){
//            throw new LinfengException(jwtUtils.getHeader() + "失效，请重新登录", HttpStatus.UNAUTHORIZED.value());
//        }

        //设置userId到request里，后续根据userId，获取用户信息


        return true;
    }

}
